import { rmSync } from 'fs'
import { join } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'
import electron from 'vite-plugin-electron'
import polyfillExports from 'vite-plugin-electron/polyfill-exports'
import renderer from 'vite-plugin-electron/renderer'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import { VueUseComponentsResolver } from "unplugin-vue-components/resolvers"
// import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import postcsspxtoviewport from 'postcss-px-to-viewport'
import WindiCSS from "vite-plugin-windicss"
import viteCompression from 'vite-plugin-compression'
import { equ } from './package-env'

rmSync('dist', { recursive: true, force: true }) // 先删除本地dist
rmSync('release', { recursive: true, force: true }) // 先删除本地release

// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require("path")

const smartPlugins = []

if (equ === 'smart') {
  smartPlugins.push(renderer())
  smartPlugins.push(polyfillExports())
  smartPlugins.push(electron({
    main: {
      entry: 'electron/main/index.ts',
      vite: {
        build: {
          sourcemap: false,
          outDir: 'dist/electron/main',
        },
        publicDir: 'public',
      },
    },
    preload: {
      input: {
        index: join(__dirname, 'electron/preload/index.ts'),
      },
      vite: {
        build: {
          sourcemap: 'inline',
          outDir: 'dist/electron/preload',
        }
      }
    },
  }))
}

// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  envPrefix: 'XMOV_APP_',
  envDir: './env',
  define: {
    __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
  },
  assetsInclude: [
    '**/*.svga'
  ],
  plugins: [
    vue(),
    VueSetupExtend(),
    vueJsx(),
    createHtmlPlugin({
      minify: true,
      entry: './src/main.ts',
      inject: {
        data: {
          title: 'Xmov 有灵虚拟数字人'
        }
      }
    }),
    WindiCSS({
      scan: {
        dirs: [__dirname], // all files in the cwd
        fileExtensions: ["vue", "js", "ts"], // also enabled scanning for js/ts
      },
    }),
    AutoImport({
      // `auto-imports.d.ts`文件生成位置 - 默认根目录
      dts: './src/typings/auto-imports.d.ts',
      imports: ['vue', 'pinia', 'vue-router', '@vueuse/core'],
      eslintrc: {
        enabled: false, // Default `false`
        filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      }
    }),
    Components({
      dts: './src/typings/components.d.ts',
      extensions: ['vue', 'md'],
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      dirs: ['src/components', 'src/biz-components'],
      resolvers: [VueUseComponentsResolver()],
    }),
    // createSvgIconsPlugin({
    //   iconDirs: [path.resolve(process.cwd(), 'src/assets/icons'), path.resolve(process.cwd(), 'src/assets/white-theme/icons')],
    //   symbolId: 'svg-icon-[name]',
    //   svgoOptions: false
    // }),
    viteCompression({
      threshold: 1024,
    }),
    ...smartPlugins
  ],
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
        @import "@/assets/styles/index.scss";
        ${equ === 'pc' ? '@import "@/assets/styles/form-pc.scss"' : '@import "@/assets/styles/form.scss"'};`
      }
    },
    postcss: {
      plugins: equ !== 'pc' ? [
        postcsspxtoviewport({
          unitToConvert: 'px', // 要转化的单位
          viewportWidth: 375, // UI设计稿的宽度
          unitPrecision: 6, // 转换后的精度，即小数点位数
          propList: ['*'], // 指定转换的css属性的单位，*代表全部css属性的单位都进行转换
          viewportUnit: 'vw', // 指定需要转换成的视窗单位，默认vw
          fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位，默认vw
          selectorBlackList: ['virtual-scroll-viewport', 'virtual-scroll-item', 'cube-wrapper'], // 指定不转换为视窗单位的类名，
          minPixelValue: 1, // 默认值1，小于或等于1px则不进行转换
          mediaQuery: false, // 是否在媒体查询的css代码中也进行转换，默认false
          replace: true, // 是否转换后直接更换属性值
        })
      ] : []
    }
  },
  server: {
    host: true,
    port: 3344,
  },
  resolve: {
    // 配置路径别名
    alias: {
      "@": path.resolve(__dirname, "./src"),
      "@main": path.resolve(__dirname, "./electron/main"),
      "@pre": path.resolve(__dirname, "./electron/preload"),
      '@images': path.resolve(__dirname, './src/assets/images'),
      '@types': path.resolve(__dirname, './src/@types'),
      "@env": path.resolve(__dirname, './package-env.ts')
    },
    // 忽略后缀名的配置选项, 添加 .vue 选项时要记得原本默认忽略的选项也要手动写入
    extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json"],
  },
  build: {
    chunkSizeWarningLimit: 200,
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_debugger: true,
      },
      output: {
        comments: true,
      },
    },
    rollupOptions: {
      external: ['public/weights']
    }
    // rollupOptions: {
    //   output: {
    //     manualChunks: (id) => {
    //       id = id.toString()
    //       if (id.includes('node_modules')) {
    //         return `vendor.${id.split('node_modules/')[1].split('/')[0]}`;
    //       } else if (id.includes('components/')) {
    //         return id.split('components/')[1].split('.')[0].split('/').filter(x => x !== 'index').join('.')
    //       } else {
    //         console.log(id)
    //       }
    //     },
    //     entryFileNames: 'js/[name].[hash].js',
    //     chunkFileNames: 'js/[name].[hash].js',
    //     assetFileNames: '[ext]/[name].[hash].[ext]',
    //   },
    // },
  }
})
